package com.zhao.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpUtils {
    private HttpUtils() {
    }

    static String sendRequest(RequestMode mode, String urlStr) throws IOException {
        final URL url = new URL(urlStr);
        final HttpURLConnection content = (HttpURLConnection) url.openConnection();
        content.setRequestMethod(mode.name());
        content.setDoInput(true);
        content.setDoOutput(true);
        content.connect();
        final InputStream is = content.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String tmpStr;
        StringBuffer buffer;
        buffer = new StringBuffer();
        while ((tmpStr = br.readLine()) != null) {
            tmpStr = new String(tmpStr.getBytes(), StandardCharsets.UTF_8);
            buffer.append(tmpStr);
        }
        br.close();
        is.close();
        content.disconnect();
        return buffer.toString();
    }

    public static String get(String url) throws IOException {
        return sendRequest(RequestMode.GET, url);
    }

    public static String post(String url) throws IOException {
        return sendRequest(RequestMode.POST, url);
    }

}